using AutoMapper;
using BasicData.Domain.Entities;
using Microsoft.IdentityModel.Tokens;
using Process.Domain.Entities;
using Produce.Application.DTO.Input;
using Produce.Application.DTO.Output;
using Produce.Domain.Entities;
using Produce.Infrastructure.Repositories;
using Produce.Result;
using SqlSugar;
using System.Collections.Generic;
using Yitter.IdGenerator;
using Microsoft.Extensions.Logging;

namespace Produce.Application.Services
{
    public class ProduceModelAppService : IProduceModelAppService
    {
        private readonly IProduceModelRepository<ProductionWorkorder> _repository;
        private readonly IMapper _mapper;
        private readonly ISqlSugarClient _db;
        private readonly IProduceModelRepository<ProductionState> _StateReq;
        private readonly ILogger<ProduceModelAppService> _logger;

        public ProduceModelAppService(
            IProduceModelRepository<ProductionWorkorder> repository,
            IMapper mapper,
            ISqlSugarClient db,
            IProduceModelRepository<ProductionState> StateReq,
            ILogger<ProduceModelAppService> logger)
        {
            _repository = repository;
            _mapper = mapper;
            _db = db;
            _StateReq = StateReq;
            _logger = logger;
        }

        /// <summary>
        /// 添加工单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult<int> AddWorkorder(AddWorkorderInput input)
        {
            var model = _mapper.Map<ProductionWorkorder>(input);
            model.Id = YitIdHelper.NextId();
            //model.Code = "MO" + DateTime.Now.ToString("yyyyMMdd") + new Random().Next(1000, 9999);
            model.State = "备料中";
            model.IsDeleted = false;
            model.CreatedAt = DateTime.Now;
            model.ProductionNumber = model.Code;
            model.Source = "Mes";
            model.Scrap = 0;
            model.Good = 0;
            model.Input = 0;
            model.Progress="0%";

            int r = _repository.Create(model);


            _StateReq.Create(new ProductionState()
            {
                Id = YitIdHelper.NextId(),
                ProductionType = "工单",
                ProductionCode = model.Code,
                Process = "",
                ProductionDateTime = DateTime.Now,
                ProduceState = false,
                ProductionDesc = "",
                CreatedBy = input.CreatedBy,
            });

            if (r > 0)
            {
                return new ApiResult<int>()
                {
                    Success = true,
                    Data = r,
                    Message = "添加工单成功"
                };
            }
            else
            {
                return new ApiResult<int>()
                {
                    Success = false,
                    Data = r,
                    Message = "添加工单失败"
                };
            }

        }

        /// <summary>
        /// 获取工单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiPaging<WorkorderOutput> GetWorkOrder(GetWorkorderInput input)
        {
            //基本查询
            var query = _repository.GetValue()
                .Where(x => x.IsDeleted == false);

            //查询条件
            if (!string.IsNullOrEmpty(input.Code))
            {
                query = query.Where(x => x.Code.Contains(input.Code));
            }
            //客户
            if (input.Client != null)
            {
                query = query.Where(x => x.Client == input.Client);
            }
            //日期
            if (input.CreatedAt != null)
            {
                // 只比较日期部分，忽略时间
                var inputDate = input.CreatedAt.Value.Date; // 获取日期部分，时间设为00:00:00
                query = query.Where(x => x.CreatedAt.Date == inputDate);
            }

            try
            {
                // 使用导航属性加载关联数据
                var count = query.Count();
                var workorders = query.OrderByDescending(x => x.Id)
                                      .Skip((input.PageIndex - 1) * input.PageSize)
                                      .Take(input.PageSize)
                                      .Includes(x => x.ProductName)  // 加载产品信息
                                      .Includes(x => x.Customer)     // 加载客户信息
                                      .Includes(x => x.LineName)     // 加载产线信息
                                      .Includes(x => x.OperationName) // 加载工艺路线信息
                                      .ToList();

                // 映射数据到输出DTO
                var outputList = workorders.Select(w =>
                {

                    var output = new WorkorderOutput
                    {
                        Id = w.Id,
                        Code = w.Code,
                        ProductionType = w.ProductionType,
                        Client = w.Client,
                        CustomerName = w.Customer?.CustomerName ?? string.Empty,
                        Masterdata = w.Masterdata ?? 0,
                        ProductName = w.ProductName?.ProductName ?? string.Empty,
                        Line = w.Line,
                        LineName = w.LineName?.LineName ?? string.Empty,
                        Operation = w.Operation,
                        OperationName = w.OperationName?.OperationName ?? string.Empty,
                        State = w.State,
                        Progress = w.Progress ?? string.Empty,
                        ProductionCount = w.ProductionCount,
                        BeginTime = w.BeginTime,
                        EndTime = w.EndTime,
                        Whether = w.Whether,
                        Img = w.Img,
                        ProductionDesc = w.ProductionDesc,
                        Input = w.Input,
                        Good = w.Good,
                        Scrap = w.Scrap,
                        Source = w.Source,
                        ProductionNumber = w.ProductionNumber,
                        CreatedBy = w.CreatedBy,
                        CreatedAt = w.CreatedAt
                    };

                    return output;
                }).ToList();

                // 返回结果
                return new ApiPaging<WorkorderOutput>
                {
                    Success = true,
                    TotalCount = count,
                    PageDate = outputList,
                    Message = "获取工单成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiPaging<WorkorderOutput>
                {
                    Success = false,
                    TotalCount = 0,
                    PageDate = new List<WorkorderOutput>(),
                    Message = $"获取工单失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 修改工单
        /// </summary>ss
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult<int> UploadWorkorder(UpdateWorkorderInput input)
        {
            var query = _repository.GetValue().First(x => x.Id == input.Id);

            var model = _mapper.Map(input, query);


            var i = _repository.Update(model);

            if (i > 0)
            {
                return new ApiResult<int>
                {
                    Success = true,
                    Message = "修改工单成功",
                    Data = i
                };
            }
            else
            {
                return new ApiResult<int>
                {
                    Success = false,
                    Message = "修改工单失败",
                    Data = i
                };
            }
        }

        /// <summary>
        /// 删除工单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult<int> DeleteWorkorder(long id)
        {
            var query = _repository.GetValue().Where(x => x.Id == id).First();

            if (query == null)
            {
                return new ApiResult<int>
                {
                    Success = false,
                    Message = "未找到该数据",
                    Data = 0
                };
            }

            query.IsDeleted = true;

            int i = _repository.Update(query);

            if (i > 0)
            {

                return new ApiResult<int>
                {
                    Success = true,
                    Message = "删除工单成功",
                    Data = i
                };
            }
            else
            {
                return new ApiResult<int>
                {
                    Success = false,
                    Message = "删除工单失败",
                    Data = i
                };
            }
        }

      
    }
}